<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'mo:order:scOrder:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    @close="handleClose"
    width="90%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span>
        {{ getTitle.value }} 【{{ record.code }} | {{ record.sortNum }} 】
        <DictLabel :dictType="'mes_mo_order_status'" :dictValue="record.orderStatus" />
      </span>
    </template>
    <!-- <BasicForm @register="registerForm" /> -->
    <Tabs v-model:activeKey="activeKey" tabPosition="left" @change="changeTabs">
      <Tabs.TabPane key="1" :forceRender="true" tab="订单信息">
        <BasicForm @register="registerForm1"> </BasicForm>
      </Tabs.TabPane>
      <Tabs.TabPane key="2" :forceRender="true" tab="订单工艺">
        <!-- <BasicForm @register="registerForm2">
          <template #ddgyList> -->
        <BasicTable @register="registerTable">
          <template #tableTitle>
            <Icon :icon="getTitle.icon" class="m-1 pr-1" />
            <span>订单工艺</span>
          </template>
          <template #toolbar v-if="record.orderStatus !== '4' && record.orderStatus !== '9'">
            <a-popconfirm
              title="是否确认刷新标准工艺？"
              ok-text="是"
              cancel-text="否"
              placement="bottom"
              @confirm="handlerouteAdd()"
            >
              <a-button type="default" v-auth="'mes:orderRoute:edit'">
                <Icon icon="ant-design:plus-circle-outlined" /> {{ t('刷新标准工艺') }}
              </a-button>
            </a-popconfirm>

            <a-button type="primary" @click="handlerouteForm()" v-auth="'mes:orderRoute:edit'">
              <Icon icon="simple-line-icons:settings" /> {{ t('工艺修改') }}
            </a-button>
          </template>
          <template #checkBox="{ record, column }">
            <a-checkbox :checked="record[column.dataIndex] == '1' ? true : false" />
          </template>
        </BasicTable>
        <!-- </template>
        </BasicForm> -->
        <routeEditList @register="registerrouteDrawer" @success="handlerouteSuccess" />
      </Tabs.TabPane>

      <Tabs.TabPane key="3" :forceRender="true" tab="产线分配">
        <BasicForm @register="registerForm3">
          <template #cxfpList>
            <BasicTable @register="registercxfpTable">
              <template #toolbar v-if="record.orderStatus !== '4' && record.orderStatus !== '9'">
                <a-button type="primary" @click="handlecxfp()" v-auth="'mes:orderLinefp:cxfp'">
                  <Icon icon="simple-line-icons:settings" /> {{ t('产线分配') }}
                </a-button>
              </template>
            </BasicTable>
          </template>
        </BasicForm>
        <cxfpModal @register="registercxfpDrawer" @success="handlecxfpSuccess" />
        <cxfpForm2 @register="registercxfpForm2Drawer" @success="handlecxfpSuccess" />
      </Tabs.TabPane>

      <Tabs.TabPane key="4" :forceRender="true" tab="任务分派">
        <!-- <BasicForm @register="registerForm4"> -->
        <BasicTable @register="registerTaskTable" @row-click="handleTaskTableRowClick">
          <template #tableTitle>
            <Icon :icon="getTitle.icon" class="m-1 pr-1" />
            <span>任务分派</span>
          </template>
          <template #toolbar v-if="record.orderStatus !== '4' && record.orderStatus !== '9'">
            <a-button type="primary" @click="handletask()" v-auth="'mes:orderTask:ryfp'">
              <Icon icon="simple-line-icons:settings" /> {{ t('人员分配') }}
            </a-button>

            <a-popconfirm
              title="是否确认暂停？"
              ok-text="是"
              cancel-text="否"
              placement="bottom"
              @confirm="handletaskStatus('5')"
            >
              <a-button type="danger" v-auth="'mes:orderTask:stop'">
                <Icon icon="ant-design:stop-outlined" /> {{ t('暂停') }}
              </a-button>
            </a-popconfirm>

            <a-popconfirm
              title="是否确认打开？"
              ok-text="是"
              cancel-text="否"
              placement="bottom"
              @confirm="handletaskStatus('2')"
            >
              <a-button type="success" v-auth="'mes:orderTask:open'">
                <Icon icon="ant-design:check-circle-outlined" /> {{ t('打开') }}
              </a-button>
            </a-popconfirm>

            <a-popconfirm
              title="是否确认关闭？"
              ok-text="是"
              cancel-text="否"
              placement="bottom"
              @confirm="handletaskStatus('9')"
            >
              <a-button type="danger" v-auth="'mes:orderTask:close'">
                <Icon icon="ant-design:close-circle-outlined" /> {{ t('关闭') }}
              </a-button>
            </a-popconfirm>
          </template>

          <template #planStartDate="{ record }">
            {{ record.planStartDate }}
          </template>
          <template #planOverDate="{ record }">
            {{ record.planOverDate }}
          </template>
        </BasicTable>
        <!-- </BasicForm> -->
        <taskForm @register="registertaskDrawer" @success="handletaskSuccess" />
      </Tabs.TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoOrderScOrderForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { ScOrder, scOrderSave, scOrderForm } from '/@/api/mes/mo/order/scOrder';
  import { basWorkShopTreeData } from '/@/api/bas/mes/workshop/basMesWorkShop';
  import { Tabs } from 'ant-design-vue';
  import { BasicTable, BasicColumn, useTable, TableAction } from '/@/components/Table';
  // import {  basMesRouteListData } from '/@/api/bas/mes/route/basMesRoute';
  import routeEditList from './routeEditList.vue';
  import cxfpModal from './cxfpForm.vue';
  import cxfpForm2 from './cxfpForm2.vue';
  import taskForm from './taskForm.vue';
  import { mesOrderRouteListData, mesOrderRouteAddRoute } from '/@/api/mes/mo/route/mesOrderRoute';
  import {
    MesOrderLinefp,
    mesOrderLinefpListData,
    mesOrderLinefpDelete,
  } from '/@/api/mes/mo/line/mesOrderLinefp';
  import {
    mesOrderTaskListData,
    mesOrderTaskstopTask,
    mesOrderTaskopenTask,
    mesOrderTaskcloseTask,
  } from '/@/api/mes/mo/task/mesOrderTask';

  import { DictLabel } from '/@/components/Dict';

  const emit = defineEmits(['success', 'register']);
  const activeKey = ref<string>('1');

  const { t } = useI18n('mo.order.scOrder');
  const { showMessage } = useMessage();
  const record = ref<ScOrder>({} as ScOrder);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增生产订单') : t('编辑生产订单'),
    value: t('生产订单'),
  }));

  // 计算属性，用于判断是否应该显示操作按钮
  const shouldDisplayActions = computed(() => {
    console.log(
      'record',
      record,
      record.value.orderStatus !== '4' && record.value.orderStatus !== '9',
    );
    return record.value.orderStatus !== '4' && record.value.orderStatus !== '9';
  });

  const inputFormSchemas1: FormSchema[] = [
    {
      label: t('基本信息'),
      field: 'jbxx',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('订单号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('订单状态'),
      field: 'orderStatus',
      component: 'Select',
      componentProps: {
        dictType: 'mes_mo_order_status',
      },
      dynamicDisabled: true,
    },
    {
      label: t('订单行号'),
      field: 'sortNum',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      dynamicDisabled: true,
      // rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },

    {
      label: t('订单日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      dynamicDisabled: true,
    },
    {
      label: t('归属车间'),
      field: 'workShopCode',
      fieldLabel: 'workShop.officeName',
      component: 'TreeSelect',
      componentProps: {
        api: basWorkShopTreeData,
        allowClear: true,
        canSelectParent: false,
        immediate: true,
      },
      dynamicDisabled: true,
    },

    {
      label: t('存货编码'),
      field: 'invCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('存货名称'),
      field: 'basInv.cinvname',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
    },
    {
      label: t('规格型号'),
      field: 'basInv.cinvstd',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
    },
    {
      label: t('数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      dynamicDisabled: true,
      // rules: [
      //   { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      // ],
    },
    {
      label: t('单位'),
      field: 'basInv.ccomunitname',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
    },

    // {
    //   label: t('计划开始'),
    //   field: 'planStartDate',
    //   component: 'DatePicker',
    //   componentProps: {
    //     format: 'YYYY-MM-DD',
    //     showTime: false,
    //   },
    //   dynamicDisabled: true,
    // },
    // {
    //   label: t('计划结束'),
    //   field: 'planOverDate',
    //   component: 'DatePicker',
    //   componentProps: {
    //     format: 'YYYY-MM-DD',
    //     showTime: false,
    //   },
    //   dynamicDisabled: true,
    // },
    {
      label: t('生产节拍（秒）'),
      field: 'taktTime',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
    },
    {
      label: t('换产时间（分）'),
      field: 'proChangeTime',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
    },
    {
      label: t('生产耗时'),
      field: 'proTakeTime',
      component: 'Input',
      componentProps: {},
      dynamicDisabled: true,
    },
    {
      label: t('执行信息'),
      field: 'zxxx',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('计划开始(车)'),
      field: 'planStartDateWork',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      colProps: { lg: 12, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('计划结束(车)'),
      field: 'planOverDateWork',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      colProps: { lg: 12, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('累计分派'),
      field: 'sumFpQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      colProps: { lg: 12, md: 24 },
      dynamicDisabled: true,
      // rules: [
      //   { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      // ],
    },
    {
      label: t('分派状态'),
      field: 'fpStatus',
      component: 'Select',
      componentProps: {
        dictType: 'mes_mo_order_fp_status',
      },
      dynamicDisabled: true,
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('完工数'),
      field: 'sumOverQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      colProps: { lg: 12, md: 24 },
      dynamicDisabled: true,
      // rules: [
      //   { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      // ],
    },
    {
      label: t('合格数'),
      field: 'sumOkQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      colProps: { lg: 12, md: 24 },
      dynamicDisabled: true,
      // rules: [
      //   { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      // ],
    },
  ];

  const inputFormSchemas3: FormSchema[] = [
    {
      label: t('订单数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('待分配数量'),
      field: 'syQty',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      // label: t(''),
      field: 'cxfpList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'cxfpList',
    },
  ];
  // const inputFormSchemas4: FormSchema[] = [
  //   // {
  //   //   label: t('订单号'),
  //   //   field: 'code',
  //   //   component: 'Input',
  //   //   componentProps: {
  //   //     maxlength: 64,
  //   //   },
  //   // },
  // ];

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('工序编码'),
        field: 'operCode',
        component: 'Input',
      },
      {
        label: t('工序名称'),
        field: 'basOper.name',
        component: 'Input',
      },
    ],
  };

  const searchFormTask: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('工序编码'),
        field: 'operCode',
        component: 'Input',
      },
      {
        label: t('工序名称'),
        field: 'basOper.name',
        component: 'Input',
      },
      {
        label: t('生产线'),
        field: 'fp.lineCode',
        component: 'Input',
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('加工顺序'),
      dataIndex: 'sortNum',
      width: 100,
      align: 'left',
      slot: 'firstColumn',
      fixed: 'left',
    },
    {
      title: t('工序编码'),
      dataIndex: 'operCode',
      width: 150,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('工序名称'),
      dataIndex: 'basOper.name',
      width: 150,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('关键工序'),
      dataIndex: 'bkey',
      width: 150,
      align: 'center',
      slot: 'checkBox',
    },
    {
      title: t('计价方式'),
      dataIndex: 'costType',
      width: 150,
      align: 'center',
      dictType: 'mes_price_mode',
    },
    {
      title: t('是否委外'),
      dataIndex: 'bout',
      width: 150,
      align: 'center',
      slot: 'checkBox',
    },
    {
      title: t('是否报工'),
      dataIndex: 'breport',
      width: 150,
      align: 'center',
      slot: 'checkBox',
    },
    {
      title: t('是否检验'),
      dataIndex: 'bcheck',
      width: 150,
      align: 'center',
      slot: 'checkBox',
    },
    {
      title: t('是否上机'),
      dataIndex: 'bmachine',
      width: 150,
      align: 'center',
      slot: 'checkBox',
    },
    {
      title: t('操作工'),
      dataIndex: 'userNames',
      width: 100,
      align: 'left',
    },
    // {
    //   title: t('技能标准'),
    //   dataIndex: 'techLevel',
    //   width: 150,
    //   align: 'center',
    //   dictType: 'mes_tech_level',
    // },
    // {
    //   title: t('技能控制'),
    //   dataIndex: 'techCtrl',
    //   width: 150,
    //   align: 'center',
    //   dictType: 'mes_tech_ctrl',
    // },
    {
      title: t('报工方式'),
      dataIndex: 'reportType',
      width: 150,
      align: 'center',
      dictType: 'mes_report_type',
    },
    {
      title: t('计件单价'),
      dataIndex: 'iprice',
      width: 150,
      align: 'right',
    },
    {
      title: t('备注'),
      dataIndex: 'remarks',
      width: 150,
      align: 'left',
    },
  ];

  const tableColumnscxfp: BasicColumn[] = [
    {
      title: t('生产线'),
      dataIndex: 'lineCode',
      width: 80,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('存货编码'),
      dataIndex: 'basInv.cinvcode',
      width: 130,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'basInv.cinvname',
      width: 200,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      width: 180,
      align: 'left',
    },

    {
      title: t('数量'),
      dataIndex: 'iqty',
      width: 80,
      align: 'right',
    },
    {
      title: t('备注'),
      dataIndex: 'remarks',
      width: 120,
      align: 'left',
    },
    {
      title: t('分配人'),
      dataIndex: 'createByName',
      width: 100,
      align: 'center',
    },
    {
      title: t('分配时间'),
      dataIndex: 'createDate',
      width: 150,
      align: 'center',
    },
    {
      title: t('修改人'),
      dataIndex: 'updateByName',
      width: 100,
      align: 'center',
    },
    {
      title: t('修改时间'),
      dataIndex: 'updateDate',
      width: 150,
      align: 'center',
    },
  ];

  const tableColumnsTask: BasicColumn[] = [
    // {
    //   title: t('订单子表ID'),
    //   dataIndex: 'modid',
    //   key: 'a.modid',
    //   sorter: true,
    //   width: 200,
    //   align: 'left',
    // },
    {
      title: t('生产线'),
      dataIndex: 'fp.lineCode',
      // key: 'a.iqty',
      // sorter: true,
      width: 80,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('顺序号'),
      dataIndex: 'orderRoute.sortNum',
      width: 70,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('工序编码'),
      dataIndex: 'operCode',
      // key: 'a.oper_code',
      // sorter: true,
      width: 80,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('工序名称'),
      dataIndex: 'basOper.name',
      width: 130,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('分派人数'),
      dataIndex: 'taskPleNum',
      key: 'a.taskPleNum',
      // sorter: true,
      width: 130,
      align: 'left',
    },
    // {
    //   title: t('工艺ID'),
    //   dataIndex: 'routeId',
    //   key: 'a.route_id',
    //   sorter: true,
    //   width: 130,
    //   align: 'left',
    // },
    {
      title: t('存货编码'),
      dataIndex: 'invCode',
      // key: 'a.inv_code',
      // sorter: true,
      width: 130,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'basInv.cinvname',
      width: 200,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      width: 160,
      align: 'left',
    },

    {
      title: t('任务数量'),
      dataIndex: 'iqty',
      width: 70,
      align: 'right',
    },
    {
      title: t('操作工'),
      dataIndex: 'userNames',
      width: 90,
      align: 'left',
    },
    {
      title: t('计件单价'),
      dataIndex: 'iprice',
      width: 80,
      align: 'center',
    },
    {
      title: t('计划开始'),
      dataIndex: 'planStartDate',
      key: 'a.plan_start_date',
      sorter: true,
      width: 140,
      align: 'center',
      slot: 'planStartDate',
    },
    {
      title: t('计划结束'),
      dataIndex: 'planOverDate',
      key: 'a.plan_over_date',
      sorter: true,
      width: 140,
      align: 'center',
      slot: 'planOverDate',
    },
    {
      title: t('完工数'),
      dataIndex: 'sumOverQty',
      key: 'a.sum_over_qty',
      sorter: true,
      width: 80,
      align: 'right',
    },
    {
      title: t('合格数'),
      dataIndex: 'sumOkQty',
      key: 'a.sum_ok_qty',
      sorter: true,
      width: 80,
      align: 'right',
    },
    {
      title: t('任务状态'),
      dataIndex: 'taskStatus',
      key: 'a.task_status',
      sorter: true,
      width: 100,
      align: 'center',
      dictType: 'mes_task_status',
      fixed: 'right',
    },
  ];

  const actionColumnTask: BasicColumn = {
    width: 120,
    actions: (record: Recordable) => [
      //  {
      //   icon: 'simple-line-icons:eye',
      //   title: t('查看人员分配'),
      //   // onClick: handlecxfpForm2.bind(this, { id: record.id }),
      //   auth: 'mo:order:scOrder:edit',
      // },
      {
        // icon: 'clarity:note-edit-line',
        // title: t('暂停'),
        color: 'error',
        label: t('暂停'),
        popConfirm: {
          title: t('是否确认暂停'),
          // confirm: handlecxfpForm2Delete.bind(this, { id: record.id }),
        },
        auth: 'mo:order:scOrder:edit',
      },
      {
        // icon: 'ant-design:delete-outlined',
        // title: t('关闭'),
        color: 'error',
        label: t('关闭'),
        popConfirm: {
          title: t('是否确认关闭'),
          // confirm: handlecxfpForm2Delete.bind(this, { id: record.id }),
        },
        auth: 'mo:order:scOrder:edit',
      },
    ],
  };

  const [registerTaskTable, taskTable] = useTable({
    api: mesOrderTaskListData,
    beforeFetch: (params) => {
      params['modid'] = record.value.id;
      return params;
    },
    columns: tableColumnsTask,
    // actionColumn: actionColumnTask,
    formConfig: searchFormTask,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    // resizeHeightOffset: 60,
    immediate: false,
    rowSelection: {
      type: 'checkBox',
    },
  });

  const [registerTable, { reload, getForm, getSelectRows }] = useTable({
    api: mesOrderRouteListData,
    beforeFetch: (params) => {
      params['modid'] = record.value.id;
      return params;
    },
    columns: tableColumns,
    // actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    // resizeHeightOffset: 60,
    immediate: false,
    //  rowSelection: {
    //   type: 'checkBox',
    // },
    pagination: false,
  });

  const actionColumn: BasicColumn = {
    width: 120,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('修改'),
        onClick: handlecxfpForm2.bind(this, { id: record.id }),
        auth: 'mes:orderLinefp:cxfp',
        // 根据shouldDisplayActions的值来判断是否显示
        ifShow: shouldDisplayActions.value,
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除'),
        popConfirm: {
          title: t('是否确认删除'),
          confirm: handlecxfpForm2Delete.bind(this, { id: record.id }),
        },
        auth: 'mes:orderLinefp:cxfp',
        ifShow: shouldDisplayActions.value,
      },
    ],
  };

  const [registercxfpTable, cxfpTable] = useTable({
    api: mesOrderLinefpListData,
    beforeFetch: (params) => {
      params['scOrder.id'] = record.value.id;
      return params;
    },
    columns: tableColumnscxfp,
    actionColumn: actionColumn,
    // formConfig: searchForm,
    showTableSetting: true,
    // useSearchForm: true,
    canResize: true,
    // resizeHeightOffset: 60,
    immediate: false,
    //  rowSelection: {
    //   type: 'checkBox',
    // },
  });

  const [
    registerForm1,
    { resetFields: resetFields1, setFieldsValue: setFieldsValue1, validate: validate1 },
  ] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas1,
    baseColProps: { lg: 12, md: 24 },
  });
  // const [registerForm2, { resetFields:resetFields2, setFieldsValue:setFieldsValue2, validate:validate2 }] = useForm({
  //   labelWidth: 120,
  //   schemas: inputFormSchemas2,
  //   baseColProps: { lg: 24, md: 24 },
  // });
  const [
    registerForm3,
    { resetFields: resetFields3, setFieldsValue: setFieldsValue3, validate: validate3 },
  ] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas3,
    baseColProps: { lg: 12, md: 24 },
  });
  // const [registerForm4, { resetFields:resetFields4, setFieldsValue:setFieldsValue4, validate:validate4 }] = useForm({
  //   labelWidth: 120,
  //   schemas: inputFormSchemas4,
  //   baseColProps: { lg: 24, md: 24 },
  // });

  async function changeTabs(e) {
    if (e == '2') {
      reload();
    }

    if (e == '3') {
      cxfpTable.reload();
    }

    if (e == '4') {
      taskTable.reload();
    }
  }

  const [registercxfpDrawer, { openDrawer: opencxfpDrawer }] = useDrawer();
  const [registertaskDrawer, { openDrawer: opentaskDrawer }] = useDrawer();
  const [registercxfpForm2Drawer, { openDrawer: opencxfpForm2Drawer }] = useDrawer();

  const [registerrouteDrawer, { openDrawer: openrouteDrawer }] = useDrawer();
  async function handlerouteForm() {
    const res = await mesOrderRouteListData({
      modid: record.value.id,
    });
    openrouteDrawer(true, { routeList: res.list, modid: record.value.id });
    // if (getSelectRows().length) {
    //   const res = await mesOrderRouteListData();
    //   openrouteDrawer(true, { routeList: res.list});
    // } else {
    //   showMessage('请选择一行数据！！');
    // }
  }

  async function handlerouteAdd() {
    const res = await mesOrderRouteAddRoute({
      modid: record.value.id,
    });
    showMessage(res.message);
    handlerouteSuccess();
  }

  //任务分派
  async function handletask() {
    if (taskTable.getSelectRows().length) {
      let arr = await taskTable.getSelectRows();
      opentaskDrawer(true, { arr });
    } else {
      showMessage('请选择一行数据！！');
    }
  }
  async function handletaskStatus(taskStatus) {
    if (taskTable.getSelectRowKeys().length) {
      let arr = taskTable.getSelectRowKeys();
      let selIds = arr.join(',');
      let res = {};
      if (taskStatus == '2') {
        res = await mesOrderTaskopenTask({ selIds, taskStatus });
      }
      if (taskStatus == '5') {
        res = await mesOrderTaskstopTask({ selIds, taskStatus });
      }
      if (taskStatus == '9') {
        res = await mesOrderTaskcloseTask({ selIds, taskStatus });
      }
      showMessage(res.message);
      handletaskSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  // 产线分配
  async function handlecxfp() {
    opencxfpDrawer(true, { arr: [record.value] });
  }

  function handlecxfpForm2(record: Recordable) {
    opencxfpForm2Drawer(true, record);
  }

  async function handlecxfpForm2Delete(record: Recordable) {
    const res = await mesOrderLinefpDelete(record);
    showMessage(res.message);
    handlecxfpSuccess();
  }

  function handlerouteSuccess() {
    reload();
  }

  async function handlecxfpSuccess() {
    cxfpTable.reload();
    const res = await scOrderForm({ id: record.value.id });
    record.value = (res.scOrder || {}) as ScOrder;
    // record.value.__t = new Date().getTime();
    setFieldsValue1(record.value);
    // setFieldsValue2(record.value);
    setFieldsValue3(record.value);
    // setFieldsValue4(record.value);
  }

  function handletaskSuccess() {
    taskTable.reload();
  }

  async function handleTaskTableRowClick(record: Recordable) {
    // record.onEdit?.(true, false);
    let arr = await taskTable.getSelectRowKeys();
    if (arr.includes(record.id)) {
      let newarr = arr.filter((item) => item != record.id);
      taskTable.setSelectedRowKeys(newarr);
    } else {
      taskTable.setSelectedRowKeys([...arr, record.id]);
    }
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    activeKey.value = data.activeKey || '1';
    await resetFields1();
    // await resetFields2();
    await resetFields3();
    // await resetFields4();
    const res = await scOrderForm({ id: data.id });
    record.value = (res.scOrder || {}) as ScOrder;
    record.value.__t = new Date().getTime();
    setFieldsValue1(record.value);
    // setFieldsValue2(record.value);
    setFieldsValue3(record.value);
    // setFieldsValue4(record.value);
    changeTabs(activeKey.value);
    setDrawerProps({ loading: false });
  });

  async function handleClose() {
    emit('success');
  }

  async function handleSubmit() {
    try {
      const data1 = await validate1();
      // const data2 = await validate2();
      const data3 = await validate3();
      // const data4 = await validate4();

      const data = {
        ...data1,
        // ...data2,
        ...data3,
        // ...data4,
      };
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // console.log('submit', params, data, record);
      const res = await scOrderSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  // 时间格式化日期，只保留年月日
  const formatDate = (date: string) => {
    if (!date) return '';
    const dateObj = new Date(date);
    const year = dateObj.getFullYear();
    const month = dateObj.getMonth() + 1;
    const day = dateObj.getDate();
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  };
</script>
